import { HeadingTypes } from "@/data/componentData/sharedComponentTypes";
import { ViewProps } from "@tarojs/components";
import { Header, WrappingText } from "@/components";
import { colors } from "@/data/shared/colors";
import "./index.scss";

export interface PriceTextProps extends ViewProps {
  price: number | string | null;
  type: HeadingTypes | "small";
  zeroAsNumber?: boolean;
  noSpacing?: boolean;
}

const formatPriceString = (price: number, zeroAsNumber: boolean) => {
  if (price === 0 && !zeroAsNumber) {
    return "免费";
  }
  return `¥ ${Math.round(price * 100) / 100}`;
};

const PriceView = ({
  price,
  type,
  className,
  zeroAsNumber = false,
  noSpacing = false,
  ...props
}: PriceTextProps) => {
  if (price === null || typeof price === "undefined") {
    return null;
  }

  // Sometimes API returns as string, sometimes as number
  const parsedPrice = +price;

  return type === "small" ? (
    <WrappingText
      color={colors.colorDark}
      className={`${className} price-view price-view-small`}
    >
      {formatPriceString(parsedPrice, zeroAsNumber)}
    </WrappingText>
  ) : (
    <Header
      type={type}
      color={colors.colorDark}
      className={`${className} price-view`}
      noSpacing={noSpacing}
      {...props}
    >
      {formatPriceString(parsedPrice, zeroAsNumber)}
    </Header>
  );
};

export default PriceView;
